package com.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.io.*;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dao.ArchiveDao;
import com.dao.FileDao;
import com.dao.LogDao;
import com.dao.UserDao;
import com.pojo.Archivepojo;
import com.pojo.Filepojo;
import com.pojo.Userpojo;
import com.service.ArchiveService;
import com.service.FileService;
import com.service.LogService;
import com.service.UserService;
import com.util.MybatisSessionFactory;

@Controller
public class UserController {
	UserService service = new UserService();
	LogService service1 = new LogService();
	ArchiveService ser = new ArchiveService();
	FileService ser1 = new FileService();

	// 登录的方法
	@RequestMapping(value = "login.action", method = RequestMethod.POST)
	@ResponseBody
	public String login(
			@RequestParam(value = "account", defaultValue = "") String account,
			@RequestParam(value = "password", defaultValue = "") String password,
			HttpServletResponse response) {
		Userpojo us = service.queryall(account, password);
		// System.out.println(password);
		if (!"1".equals(us.getCounter())) {
			return "ERR";
		}
		response.addCookie(new Cookie("user", us.getId()));
		service1.addlog(us.getId(), "0", "登录");
		return "OK";
	}

	// 添加
	@RequestMapping(value = "/add.action", method = RequestMethod.POST)
	@ResponseBody
	public String add(
			@RequestParam(value = "id", defaultValue = "") String id,
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "0") String sp,
			@RequestParam(value = "fc", defaultValue = "0") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {
		List<Archivepojo> ar = ser.queryall(archive_id, identity);
		// System.out.println(ar.size());
		if (0 != ar.size()) {
			return "REE";
		}
		ser.addarchive(userId, archive_id, identity, name, gender, birthday,
				date_retire1, date_retire2, sp, fc, title, seniority);
		Map<String, Object> result1 = ser.queryid();
		// System.out.println(result1);
		service1.addlog(userId, result1.get("id").toString(), "添加档案");
		return "OK";
	}

	// 修改数据
	@RequestMapping(value = "/update.action", method = RequestMethod.POST)
	@ResponseBody
	public String update(
			@RequestParam(value = "id", defaultValue = "") String id,
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "0") String sp,
			@RequestParam(value = "fc", defaultValue = "0") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {
		System.out.println(id);
		ser.update(id, userId, archive_id, identity, name, gender, birthday,
				date_retire1, date_retire2, sp, fc, title, seniority);
		service1.addlog(userId, id, "修改");
		return "OK";
	}

	// 退出登录
	@RequestMapping(value = "quit.action", method = RequestMethod.POST)
	@ResponseBody
	public String quit(
			@CookieValue(value = "user", defaultValue = "") String userId,
			HttpServletResponse response) {
		service1.addlog(userId, "0", "退出");
		response.addCookie(new Cookie("user", null));
		return "OK";
	}

	// 模糊查询
	@RequestMapping(value = "query.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Archivepojo> query(
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {

		List<Archivepojo> map = ser.query(userId, archive_id, identity, name,
				gender, birthday, date_retire1, date_retire2, sp, fc, title,
				seniority);
		return map;
	}

	// 最近浏览
	@RequestMapping(value = "queryone.action", method = RequestMethod.POST)
	@ResponseBody
	public String queryone(
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "search", defaultValue = "") String search,
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletResponse response) {
		List<Archivepojo> map = ser.queryone(search);
		// System.out.println(map);
		if (0 == map.size()) {
			return "REE";
		} else if (1 < map.size()) {
			return "REE2";
		}
		service1.addlog(userId, map.get(0).getId(), "浏览");
		return map.get(0).getId();
	}

	// 照片的ID
	@RequestMapping(value = "queryfile.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Filepojo> queryfile(
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletResponse response) {
		List<Filepojo> map = ser1.queryfile(id);
		System.out.println(map);
		return map;
	}

	// 显示照片
	@RequestMapping(value = "queryjpg.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> queryjpg(
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletResponse response) {
		SqlSession session = MybatisSessionFactory.getSqlSession();
		FileDao c = session.getMapper(FileDao.class);
		List<Map> map = c.queryjpg(id);
		// System.out.println(map);
		return map;
	}

	@RequestMapping(value = "queryjp.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> queryjp(
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletResponse response) {
		SqlSession session = MybatisSessionFactory.getSqlSession();
		FileDao c = session.getMapper(FileDao.class);
		System.out.println(id);
		List<Map> map = c.queryjp(id);
		System.out.println(map);
		return map;
	}

	// 查询用户
	@RequestMapping(value = "queryl.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> queryl(
			@CookieValue(value = "user", defaultValue = "") String userId,
			HttpServletResponse response) {
		SqlSession session = MybatisSessionFactory.getSqlSession();
		ArchiveDao c = session.getMapper(ArchiveDao.class);
		List<Map> map = c.queryl(userId);
		return map;
	}

	// 用户信息
	@RequestMapping(value = "queryt.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> queryt(
			@CookieValue(value = "user", defaultValue = "") String userId,
			HttpServletResponse response) {
		SqlSession session = MybatisSessionFactory.getSqlSession();
		ArchiveDao c = session.getMapper(ArchiveDao.class);
		List<Map> map = c.queryt(userId);
		return map;
	}

	// 查询一个ID
	@RequestMapping(value = "query_one.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Archivepojo> query_one(
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletResponse response) {
		List<Archivepojo> map = ser.query_one(id);
		return map;

	}

	// 删除
	@RequestMapping(value = "dele.action", method = RequestMethod.POST)
	@ResponseBody
	public String dele(
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletResponse response) {
		ser.dele(id);
		service1.addlog(userId, id, "删除");
		return "OK";
	}

	// 删除照片
	@RequestMapping(value = "deletephoto.action", method = RequestMethod.POST)
	@ResponseBody
	public String deletephoto(
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletRequest req) {
		SqlSession session = MybatisSessionFactory.getSqlSession();
		FileDao d = session.getMapper(FileDao.class);
		Map<String, Object> fil = d.queryjg(id);
		String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
				.getServletContext().getRealPath("/"), "upload", fil.get("ac"),
				fil.get("fn"));
		// System.out.println( archive.get(0).getArchive_id());
		File existsFile = new File(filePath);
		System.out.println(filePath);
		existsFile.delete();
		ser1.deletephoto(id);
		System.out.println(id);
		session.commit();
		return "OK";
	}

	// 照片的上传
	@RequestMapping(value = "/{id}/upload.action", method = RequestMethod.POST)
	@ResponseBody
	public String upload(
			@CookieValue(value = "user", defaultValue = "") String userId,
			HttpServletResponse response, @PathVariable String id,
			@RequestParam("file") MultipartFile file, HttpServletRequest req) {
		if (file.isEmpty()) {
			System.out.println("未选择文件");
			return "ERROR_NO_FILE";
		}
		try {
			byte[] bytes = file.getBytes();
			String fileName = file.getOriginalFilename();
			String fileExtension = fileName
					.substring(fileName.lastIndexOf(".") + 1);
			String newFileName = String.valueOf(System.currentTimeMillis())
					+ "." + fileExtension;
			SqlSession Session = MybatisSessionFactory.getSqlSession();
			ArchiveDao dao = Session.getMapper(ArchiveDao.class);
			List<Archivepojo> archive = dao.query_one(id);
			// System.out.println(id);
			String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
					.getServletContext().getRealPath("/"), "upload",
			// "1111",

					archive.get(0).getArchive_id().toString(), newFileName);
			// System.out.println(filePath);
			// System.out.println( archive.get(0).getArchive_id());
			File existsFile = new File(filePath);
			if (!existsFile.getParentFile().exists()) {
				if (!existsFile.getParentFile().mkdirs()) {
					System.out.println("创建目录失败");
					return "ERROR_ON_MKDIR";
				}
			}
			if (existsFile.exists()) {
				if (existsFile.delete()) {
					// System.out.println("删除原始文件：" + filePath);
				} else {
					System.out.println("删除文件失败：" + filePath);
				}
			}
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(new File(filePath)));
			stream.write(bytes);
			stream.close();
			ser1.addfile(id, newFileName);
			service1.addlog(userId, id, "上传");
			Session.commit();
			return "OK";
		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
		}
	}
	// 根据时间段统计
	@RequestMapping(value = "queryg.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Map> queryg(
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "date1", defaultValue = "") String date1,
			@RequestParam(value = "date2", defaultValue = "") String date2,
			HttpServletResponse response) {
		SqlSession session = MybatisSessionFactory.getSqlSession();
		LogDao d = session.getMapper(LogDao.class);
		List<Map> map = d.queryg(date1, date2);
		return map;
	}
}
